package com.kaifamiao.req;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.logging.Logger;

@WebServlet( "/parse/request" )
public class ParseRequestServlet extends HttpServlet {

    private Logger logger = Logger.getLogger( this.getClass().getName() );

    @Override
    protected void service( HttpServletRequest request , HttpServletResponse response )
            throws ServletException, IOException {
        request.setCharacterEncoding( "UTF-8" );

        logger.info( "请求行" );
        String method = request.getMethod() ; // 获得请求方法(对应HTTP动作)
        String uri = request.getRequestURI() ; // 获取本次请求所访问的资源路径
        String protocol = request.getProtocol(); // 获取请求协议和版本
        System.err.println( method + " " + uri + " " + protocol );

        String query = request.getQueryString();
        if( query != null ) {
            // 使用 java.net.URLDecoder 的 decode 方法可以将 "%E5%BC%A0" 解析为 "张"
            String decoded = URLDecoder.decode(query, "UTF-8");
            System.err.println( "查询字符串(QueryString): " + query + " / " + decoded);
        }

        logger.info( "请求头" );
        // 获取所有的请求头字段的名称
        Enumeration<String> headerNames = request.getHeaderNames();
        Iterator<String> itor = headerNames.asIterator();
        while( itor.hasNext() ){
            String headerName = itor.next();
            // 根据请求头字段的名称获取取值
            String headerValue = request.getHeader( headerName );
            System.err.println( headerName + ":" + headerValue );
        }

        logger.info( "请求体" );
        // 暂时先以字符形式读取请求体中的内容
        BufferedReader br = request.getReader();
        String line ;
        // BufferedReader 的 readLine 方法可以读取文本中的一行数据，若到达流末尾则返回 null
        while( ( line = br.readLine() ) != null ) {
            System.err.println( line );
        }
    }

}
